package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.BorrowedDTO;
import com.lastproject.dto.EmailGroupDTO;
import com.lastproject.dto.QuestionDTO;
import com.lastproject.ejb.entities.Borrowed;
import com.lastproject.ejb.entities.EmailGroup;
import com.lastproject.ejb.entities.Question;
import com.lastproject.ejb.util.EmailGroupConversion;

/**
 * Session Bean implementation class GroupDAO
 */
@Stateless
public class EmailGroupDAO implements EmailGroupDAORemote {

    /**
     * Default constructor. 
     */
	@PersistenceContext (unitName = "LastProjectEJB")
	private EntityManager em;
	
	@EJB
	private EmailGroupConversion conv;
	
    public EmailGroupDAO() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void create(EmailGroupDTO groupDTO) {
		em.persist(conv.fromDTO(groupDTO));
		
	}

	@Override
	public void edit(EmailGroupDTO groupDTO) {
		em.merge(conv.fromDTO(groupDTO));
		
	}

	@Override
	public void remove(EmailGroupDTO groupDTO) {
		EmailGroup b = em.find(EmailGroup.class,
				conv.fromDTO(groupDTO).getId());
		em.remove(b);
		
	}

	@Override
	public EmailGroupDTO findByID(Object id) {
		EmailGroup g = em.find(EmailGroup.class,id);
		EmailGroupDTO group = conv.fromEntity(g);
		return group;
	}

	@Override
	public List<EmailGroupDTO> findAll() {
		List<EmailGroup> groupList = (List<EmailGroup>) em.createNamedQuery("EmailGroup.findAll", EmailGroup.class).getResultList();
		List<EmailGroupDTO> groupDTO = new ArrayList<EmailGroupDTO>();
		
		for(EmailGroup b:groupList){
			EmailGroupDTO group = new EmailGroupDTO();
			group = conv.fromEntity(b);
			groupDTO.add(group);
		}
		return groupDTO;
	}

	@Override
	public EmailGroupDTO findLastByName(String name) {
		List<EmailGroup> groups = new ArrayList<EmailGroup>();
		groups = em.createNamedQuery("EmailGroup.findLastByName", EmailGroup.class).setParameter("name", name).getResultList();
		if (groups.size() != 0)
			return conv.fromEntity(groups.get(groups.size()-1));
		return null;
	}

	@Override
	public List<EmailGroupDTO> findGroupsByUserId(int id) {
		List<EmailGroup> groups = em.createQuery("SELECT e FROM EmailGroup e INNER JOIN e.users u WHERE u.id =:id",
				EmailGroup.class).setParameter("id", id).getResultList();
		
		List<EmailGroupDTO> groupsListByUserId = new ArrayList<EmailGroupDTO>();

		if(groups.size()!=0)
			for (EmailGroup group : groups) {
				EmailGroupDTO g = new EmailGroupDTO();
				g = conv.fromEntity(group);
				groupsListByUserId.add(g);
			}

		return groupsListByUserId;
	}

}
